package com.study.controller;


import com.study.bean.User;
import com.study.service.UserService;
import com.study.service.impl.UserServiceImpl;
import com.study.util.JSONUtil;
import com.study.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/user")
public class UserController extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        switch (method){
            case "login":
                try {
                    login(req, resp);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                break;
        }
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws SQLException {
        System.out.println("UserServlet.login");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        String code = req.getParameter("code");
        //先判断验证码是不是正确
        //1、验证码错误，返回一个验证码错误的提示
        //2、验证码正确，再验证验证码是不是正确
        HttpSession session = req.getSession();
        String codeInSession = (String) session.getAttribute("codeInSession");
        if (!codeInSession.equalsIgnoreCase(code)) {
            JSONUtil.toJSON(resp, Result.error("验证码错误"));
            return;
        }

        User user = userService.getUserByLogin(name, password);
        if (user == null) {
            JSONUtil.toJSON(resp, Result.error("用户名或者密码错误"));
        } else {
            session.setAttribute("user", user);
            JSONUtil.toJSON(resp, Result.ok("登录成功"));
        }

    }
}
